#!/usr/bin/env python
# coding:utf-8

from PyQt4 import QtGui
from sql_rice.gui.method_wrapper import MethodWraper
from functools import partial

SEARCH, UPDATE, DELETE, ADD = list(range(1, 5))

class ActionArea(QtGui.QToolBar):
    """Se enecarga de ejecutar las accioens sobre una ventana y un DBset"""

    def __init__(self, parent):
        QtGui.QToolBar.__init__(self)
        self.register = {}
        self.actions = {}
        self.parent = parent
        self.icon = {SEARCH: 'edit-find', UPDATE: 'document-edit',
                     ADD: 'document-new', DELETE: 'edit-delete'}
        act = QtGui.QAction(QtGui.QIcon.fromTheme('edit-clear'), 'Clear', None)
        act.activated.connect(partial(self.update, values={}, mode=DELETE))
        self.addAction(act)
        
    def collect_values(self):
        """collect_values()->dict"""
        values = {}
        status = self.parent.valide()
        if False in list(status.values()):
            raise ValueError(status)
        for name, widget in list(self.parent.widgets.items()):
            values[name] = widget.value
        for name, value in list(self.register.items()):
            values['old_' + name] = value
        return {'params': values}

    def update(self, values, mode=SEARCH):
        """update(values:dict, mode:int)->None
        mode = SEARCH | UPDATE | DELETE | ADD"""
        if mode == SEARCH:
            values = values[0] if values else {}
            self.register = values
            self.parent.update(values)
        elif mode == UPDATE:
            values = self.actions[SEARCH](params=self.register)
            self.update(values)
        elif mode == DELETE:
            self.register = {}
            self.parent.update({})
        elif mode == ADD:
            values = self.actions[SEARCH](params=self.collect_values()['params'])
            self.update(values)

    def add(self, name, label ,callback):
        """add(name:str, callback:func)-> None"""
        if name in (SEARCH, UPDATE, DELETE, ADD):
            func = MethodWraper(callback, None, partial(self.update,
                                 mode=name), self.collect_values)
        else:
            func = MethodWraper(callback, None, self.update,
                                self.collect_values)
        self.actions[name] = func
        action = QtGui.QAction(QtGui.QIcon.fromTheme(self.icon.get(name)), 
                label, self.parent)
        action.activated.connect(func)
        self.addAction(action)

